import pickle
from datetime import datetime

import tweepy
import pandas as pd
from tqdm import tqdm

API_KEY = r"TodVaEojMCKhmz3CGakmXMp5k"
API_KEY_SECRET = r"nfYcfBcFFWjuvLL4fiGDy7I0OYli2AvZIRJpekfn4UHgp7dZO4"
SAFE_BEARER_TOKEN = r"AAAAAAAAAAAAAAAAAAAAAKFehQEAAAAAJmsZkV3oer0dPMEDZQPvSOB4stQ%3DKOD29uDom8HOX9nWoQ7VAEy8Ky257b0FUkwN8ErW9hCvvFAb8t"

class TweetFetch:

    def __init__(self) -> None:

        self.client = tweepy.Client(
            bearer_token=SAFE_BEARER_TOKEN,
            wait_on_rate_limit=True)

    def fetch_multiple_user_tweets(self, usernames, start_time):
        tweets = []
        for username in usernames:
            tweets += self.fetch_user_tweets(username, start_time)
        return tweets

    def fetch_user_tweets(self, username, start_time):

        print(f"Fetching tweets of {username}")
        query = f'from:{username} -is:retweet'

        tweets_list = []
        for tweet in tqdm(tweepy.Paginator(self.client.search_all_tweets,
                                      query = query,
                                      tweet_fields = ['created_at', 'public_metrics'],
                                      max_results = 500,
                                      start_time = start_time).flatten()):

        # for tweet in tweets.data:
            tweets_list.append(dict(
                id = tweet.id,
                username = username,
                time = tweet.created_at,
                **tweet.public_metrics,
                text = tweet.text
            ))

        return tweets_list

def save_to_excel(tweets):
    with open("dump.pickle", "wb") as fp:
        pickle.dump(tweets, fp)

    dataframe = pd.DataFrame.from_dict(tweets)
    dataframe['time'] = dataframe['time'].dt.tz_localize(None)
    dataframe.to_excel("tweets.xlsx", engine='xlsxwriter')

def main():

    tf = TweetFetch()
    start_time = datetime(2011, 3, 15)
    tweets = tf.fetch_multiple_user_tweets(
        ["dbdevletbahceli", "meral_aksener", "umitozdag"], start_time)
    save_to_excel(tweets)
    # username, time, link, tweet content, like count, rt count, count

if __name__ == "__main__":
    main()
